<template xmlns:el-col="http://www.w3.org/1999/html">
    <div>
<!--      面包屑导航区域-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
<!--      卡片视图区域-->
      <el-card>
<!--        添加角色按钮区域-->
        <el-row>
          <el-col><el-button type="primary" @click="showAddRoleDialog">添加角色</el-button></el-col>
        </el-row>
<!--        角色列表区域-->
        <el-table :data="rolesList" border stripe>
<!--          展开列-->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row v-for="(item1,index1) in scope.row.children"
                      :key="item1.id"
                      :class="['bdbottom',index1===0?'bdtop':'','vcenter']" >
<!--                渲染一级权限 :span设置所占的列数-->
                <el-col :span="5">
                  <el-tag closable @close="removeRightById(scope.row,item1.id)" >{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
<!--                渲染二级和三级权限-->
                <el-col :span="19">
<!--                  通过for循环 嵌套渲染二级权限-->
                  <el-row v-for="(item2,index2) in item1.children"
                          :key="item2.id"
                          :class="[index2===0?'':'bdtop','vcenter']" >
                    <el-col :span="6">
<!--                      closable 可删除标签 @close 删除触发的事件-->
                      <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
<!--                    通过for循环 嵌套渲染三级权限-->
                    <el-col :span="18">
                      <el-tag v-for="(item3,index3) in item2.children" :key="item3.id"
                              type="warning" closable @close="removeRightById(scope.row,item3.id)">
                        {{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
<!--              <pre>展开数据的结构-->
<!--              <pre>{{scope.row}}</pre>-->
            </template>
          </el-table-column>
<!--          索引列-->
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="roleName" label="角色名称" ></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述" ></el-table-column>
          <el-table-column label="操作" width="300px" >
            <template slot-scope="scope">
<!--              修改按钮 size设置按钮的尺寸-->
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
<!--              删除按钮-->
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleById(scope.row.id)">删除</el-button>
<!--              分配权限按钮-->
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
<!--      分配权限对话框-->
      <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
<!--        树形控件show-checkbox 显示复选框 node-key 为每个树节点绑定唯一标识的属性
            default-expand-all 默认展开所有树节点 default-checked-keys默认勾选的节点的 key 的数组-->
        <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id"
                 default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
      </el-dialog>
<!--      添加角色对话框-->
      <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="50%" @close="addRoleDialogClosed">
        <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>
<!--      修改对话框-->
      <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item label="角色名称">
            <el-input v-model="editForm.roleName" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRole">确 定</el-button>
        </span>
      </el-dialog>

    </div>
</template>

<script>
  export default {
    name: 'Roles',
    data(){
      return{
        // 所有角色列表数据
        rolesList:[],
        //控制分配权限对话框显示与隐藏
        setRightDialogVisible:false,
        //所有权限的数据
        rightList:[],
        //树形控件的属性绑定对象
        treeProps:{
          label:'authName',
          children:'children'
        },
        //默认选中的节点id值数组
        defKeys:[],
        //当前即将分配权限的角色id
        roleId:'',
        //控制添加角色对框的显示与隐藏
        addRoleDialogVisible:false,
        //添加角色的表单数据
        addRoleForm:{
          roleName:'',
          roleDesc:''
        },
        //添加角色表单的验证规则对象
        addRoleFormRules:{
          roleName:[
            {required:true,message:'请输入角色名称',trigger:'blur'}
          ],
          roleDesc:[
            {required:true,message:'请输入角色描述',trigger:'blur'}
          ]
        },
        //控制编辑对框的显示与隐藏
        editDialogVisible:false,
        //编辑角色的表单数据
        editForm:{},
        //添加角色表单的验证规则对象
        editFormRules:{
          roleDesc:[
            {required:true,message:'请输入角色描述',trigger:'blur'}
          ]
        },
      }
    },
    created() {
      // 获取所有角色
      this.getRolesList()
    },
    methods:{
      //获取所有角色列表
     async getRolesList(){
       const {data:res}=await this.$http.get('roles')
       if(res.meta.status!==200){
         return this.$message.error(res.meta.msg)
       }
       // console.log(res)
       this.rolesList=res.data
       console.log(this.rolesList)
     },
      // 根据id 删除对应的权限
      async removeRightById(role,rightId){
       // 弹框提示用户是否要删除
        const confirmResult=await this.$confirm('此操作将永久删除该权限, ' +
          '是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(confirmResult!=='confirm') {
          return this.$message.info('取消删除！')
        }
        //删除角色指定权限
        const {data:res}=await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if(res.meta.status!==200){
          return this.$message.error(res.meta.msg)
        }
        //重新刷新角色权限列表，页面的完整渲染
        // this.getRolesList()
        //重新给角色赋值权限，不需要页面的完整渲染
        role.children=res.data
        this.$message.success('删除成功！')
      },
      //展示分配权限的对话框
      async showSetRightDialog(role){
       //角色的id
       this.roleId=role.id
       //获取所有权限处理
        const {data:res}=await this.$http.get('rights/tree')
        if(res.meta.status!==200){
          return this.$message.error(res.meta.msg)
        }
        //把获取到的权限数据保存到data中
        this.rightList=res.data
        //递归获取三级节点的id
        this.getLeafKeys(role,this.defKeys)
        console.log(this.defKeys)
        //显示分配权限对话框
       this.setRightDialogVisible=true
      },
      //通过递归的形式，获取角色下所有三级权限的id,并保存到defKeys数组中
      getLeafKeys(node,arr){
       //如果当前node 节点不包含children属性，则是三级节点
        if(!node.children){
          return arr.push(node.id)
        }
        node.children.forEach(item=>{
          this.getLeafKeys(item,arr)
        })
      },
      //监听分配权限对话框的关闭事件
      setRightDialogClosed(){
       //重置
       this.defKeys=[]
      },
      //点击为角色分配权限
      async allotRights(){
       //getCheckedKeys被选中的节点所组成的数组 getHalfCheckedKeys目前半选中的节点的 key 所组成的数组 ...将数组元素展开
       const keys=[
         ...this.$refs.treeRef.getCheckedKeys(),
         ...this.$refs.treeRef.getHalfCheckedKeys()
       ]
        console.log(keys)
        console.log(this.$refs.treeRef.getCheckedKeys())
        //将数组转为字符串，并用','连接
        const idStr=keys.join(',')
        console.log(idStr)
        //角色授权请求
        const {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
        console.log(res)
        if(res.meta.status!==200){
          return this.$message.error('分配权限失败！')
        }
        this.$message.success('分配权限成功！')
        //重新刷新角色列表
        this.getRolesList()
        //隐藏分配权限对话框
        this.setRightDialogVisible=false
      },
      //显示添加角色对话框
      showAddRoleDialog(){
       this.addRoleDialogVisible=true
      },
      //监听添加角色对话框的关闭事件
      addRoleDialogClosed(){
       this.$refs.addRoleFormRef.resetFields()
      },
      //点击按钮，添加角色信息并保存
      addRole(){
       this.$refs.addRoleFormRef.validate(async valid=>{
         if (!valid) return
         const {data:res}=await this.$http.post('roles',this.addRoleForm)
         if (res.meta.status!==201){
           return this.$message.error(res.meta.msg)
         }
         this.$message.success(res.meta.msg)
         this.getRolesList()
         this.addRoleDialogVisible=false
       })
      },
      //显示编辑对话框
      async showEditDialog(id){
       //根据id查询角色
       const {data:res}=await this.$http.get('roles/'+id)
        if (res.meta.status!==200){
          return this.$message.error(res.meta.msg)
        }
        //保存查询到的角色信息
        this.editForm=res.data
        console.log(this.editForm)
        this.editDialogVisible=true
      },
      //监听编辑角色对话框关闭事件
      editDialogClosed(){
       this.$refs.editFormRef.resetFields()
      },
      //点击按钮，修改角色信息并保存
      editRole(){
       this.$refs.editFormRef.validate(async valid=>{
         if(!valid) return
         const {data:res}=await this.$http.put(`roles/${this.editForm.roleId}`,{roleName:this.editForm.roleName,roleDesc:this.editForm.roleDesc})
         if (res.meta.status!==200){
           return this.$message.error(res.meta.msg)
         }
         this.$message.success(res.meta.msg)
         this.getRolesList()
         this.editDialogVisible=false
       })
      },
      //点击按钮，弹出删除角色弹窗
      async removeRoleById(id){
        const confirmResult=await this.$confirm(
          '此操作将永久删除该角色, 是否继续?',
          '提示',
          {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }
        ).catch(err=>{return err})

        // 如果用户确认了删除，则返回值为字符串 confirm
        // 如果用户取消了删除，则返回值为字符串 cancel
        if(confirmResult!=='confirm'){
          return this.$message.info('已取消删除')
        }
        const {data:res}=await this.$http.delete('roles/'+id)
        if(res.meta.status!==200){
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getRolesList()

      }
    }

  }
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
  .bdtop{
    border-top: 1px solid #eee;
  }
  .bdbottom{
    border-bottom: 1px solid #eee;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
